<template>
  <!-- 选取当前权限下的菜单资源 -->
  <a-modal
    destroy-on-close
    :visible="visible"
    :confirm-loading="loadingState.submit"
    title="选择快捷功能"
    width="420px"
    ok-text="提交"
    :footer="null"
    :closable="false"
    dialogClass="custom-modal-wrapper"
  >
    <div v-loading="loadingState.loadResource">
      <div class="tree-wrapper">
        <a-tree
          v-if="treeData.length"
          v-model="checkedKeys"
          :default-expanded-keys="defaultExpandedKeys"
          checkable
          :auto-expand-parent="true"
          :tree-data="treeData"
        />
        <Empty class="empty-box" v-else />
      </div>
      <div class="footer-wrapper">
        <a-button type="default" @click="handleCancel">取消</a-button>
        <a-button class="ml12" type="primary" :loading="loadingState.isSubmit" @click="handleOk">确认</a-button>
      </div>
    </div>
  </a-modal>
</template>

<script>
import BaseModal from '@/components/BaseModal'
import { getMenuIcon } from '@/utils/util.js'
import { Empty } from 'ant-design-vue'

export default {
  name: 'SelectMenu',
  components: {
    BaseModal,
    Empty,
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    initCheckedKeys: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      defaultExpandedKeys: [], // 默认展开的节点keys
      checkedKeys: [], // 勾选的节点keys
      treeData: [],
      loadingState: {
        submit: false,
        loadResource: false
      }
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getMenuReq()
        }
      }
    }
  },
  methods: {
    async getMenuReq() {
      try {
        this.treeData = []
        this.loadingState.loadResource = true
        await this.$store.dispatch('GetMenus')
        this.flatTreeData()
      } catch (e) {
        console.error(e)
      }
      this.loadingState.loadResource = false
    },
    /**
     * 将菜单树打造成一级结构（便于后续取值）
     */
    flatTreeData() {
      const menuTree = this.$store.state.user.menus.filter((item) => {
        return getMenuIcon(item.raw?.code)
      })
      this.treeData = menuTree
      const allList = []
      // rootCode 记录根节点的code，用以区分属于哪个模块
      const dfs = (list, level = 1, rootCode = '') => {
        list &&
          list.forEach((item) => {
            // 树节点相关字段值
            item.title = item.raw?.name || ''
            item.key = item.id
            item.checkable = level === 3
            const target = {
              title: item.title,
              key: item.id,
              id: item.id,
              pId: item.parentId,
              level: level,
              value: item.raw?.value || '', // 菜单路径
              code: item.code || item.raw?.code || '',
              rootCode
            }
            allList.push(target)
            dfs(item.children, level + 1, rootCode || target.code)
          })
      }
      dfs(menuTree)
      this.allList = allList
      // 如果有数据，则将选中节点展开
      if (this.treeData.length) {
        this.defaultExpandedKeys = []
        this.checkedKeys = this.initCheckedKeys.map((item) => {
          this.defaultExpandedKeys.push(item.pId)
          return item.key
        })
      }
    },
    handleOk() {
      if (!this.treeData.length) {
        this.$message.warning('无可选数据')
        return
      }
      if (this.loadingState.submit) return
      this.loadingState.submit = true
      const list = this.allList.filter((item) => {
        // 只获取三级菜单
        return this.checkedKeys.includes(item.key) && item.level === 3
      })
      this.$emit('confirm', list)
      this.loadingState.submit = false
    },
    handleCancel() {
      this.$emit('update:visible', false)
    }
  }
}
</script>
<style lang="less">
.custom-modal-wrapper {
  .ant-modal-header {
    padding: 40px;
    padding-bottom: 16px;
    border: none;
    .ant-modal-title {
      font-size: 16px;
      color: #333333;
      font-weight: bolder;
    }
  }
  .ant-modal-body {
    padding: 40px;
    padding-top: 0;
  }
  .ant-modal-content {
    border: 1px solid #ffffff;
    border-radius: 8px;
    box-shadow: 3px 2px 20px 0px rgba(24, 48, 60, 0.16);
  }
}
</style>
<style lang="less" scoped>
@deep: ~'>>>';
.tree-wrapper {
  border: 1px solid #eeeeee;
  height: 412px;
  overflow: auto;
  position: relative;
  .empty-box {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}
.footer-wrapper {
  padding-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>